type eventType="downloadEnd"|"uploadEnd";

class Emitter {
    //事件管理
    static events: Map<any, Map<eventType, Function[]>> =
      new Map();
    private static contains(ele:any, event: eventType, callback: Function):boolean{
        let eventMap=this.events.get(ele);
        if(!eventMap) return false;
        let callBackLists=eventMap.get(event);
        if(!callBackLists) return false;
        for(let func of callBackLists){
            if(func==callback) return true;
        }
        return false;
    }
    static once(ele:any, event: eventType, callback: Function) {
      if(this.contains(ele,event,callback)) return;
      const cb = (...args: any[]) => {
        callback(...args);
        this.off(ele, event, cb);
      };
      this.on(ele, event, cb);
    }
    static off(ele: any, event: eventType, callback: Function) {
      let e = this.events.get(ele);
      if (e) {
        const callbackList = e.get(event);
        if (callbackList && callbackList.indexOf(callback) != -1) {
          callbackList.splice(callbackList.indexOf(callback), 1);
        }
      };
    }
    static on(
      ele: any,
      event: eventType,
      callback: Function
    ): Function {
      if(this.contains(ele,event,callback)) return;
      if (!this.events.has(ele)) {
        this.events.set(ele, new Map());
      }
      //是否已经存过
      let e = this.events.get(ele);
      if (e.get(event)) e.get(event).push(callback);
      //第一次存
      else e.set(event, [callback]);
      return callback;
    }
  
    static emit(ele: any, event: eventType, ...args: any[]) {
      if (!ele) return;
      let e = this.events.get(ele);
      if (e) {
        const callbackList = e.get(event);
        if (callbackList) {
          callbackList.forEach((callback) => {
            callback(...args);
          });
        }
      }
    }}
  export default Emitter;